<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:leave_category:add']"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:leave_category:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:leave_category:remove']"
        >删除
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="假期名称" align="center" prop="name"></el-table-column>
      <el-table-column label="应用范围" align="center" prop="name">
        <template slot-scope="scope">
          {{ scope.row.deptIds !== '0' ? '部门/人员' : '全公司' }}
        </template>
      </el-table-column>
      <el-table-column label="是否带薪" align="center" prop="name">
        <template slot-scope="scope">
          {{ scope.row.isMoney ? '带薪假' : '非带薪假' }}
        </template>
      </el-table-column>
      <el-table-column label="最小请假单位" align="center" prop="name">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_unit_type" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:leave_category:edit']"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:leave_category:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body class="my-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="假期名称" prop="nickName">
              <el-input v-model="form.name" placeholder="请输入假期名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否带薪" prop="type">
              <el-select v-model="form.isMoney" placeholder="请选择是否带薪">
                <el-option
                  v-for="item in isPayMoney"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小请假单位" prop="phonenumber">
              <el-select v-model="form.unit" placeholder="请选择最小请假单位">
                <el-option
                  v-for="item in dict.type.sys_unit_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用范围" prop="phonenumber">
              <el-select v-model="scope" placeholder="请选择最小请假单位">
                <el-option
                  v-for="item in scopeType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="padding-left: 35px" v-if="scope==2">
            <org-items v-model="select" @selectOrg="selectOrg()" @detelData="detelData"/>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <org-picker multiple ref="orgPicker" :selected="select" @ok="selected" @sonIdfn="sonIdfn" :sonLine="sonLine"/>
  </div>
</template>

<script>
import {listLeave, getLeave, addLeave, updateLeave, delLeave} from '@/api/system/leave_category'
import commonData from "@/utils/commonData"
import OrgPicker from "@/components/common/OrgPicker";
import OrgItems from "@/views/approval/design/common/process/OrgItems";


export default {
  name: "Post",
  dicts: ['sys_unit_type'],
  components: {OrgPicker, OrgItems},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      isPayMoney: [
        {
          value: 1,
          label: '带薪假'
        },
        {
          value: 0,
          label: '非带薪假'
        },
      ],
      scopeType: [
        {
          value: 1,
          label: '全公司'
        },
        {
          value: 2,
          label: '部门/人员'
        },
      ],
      scope: 1,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "岗位名称不能为空", trigger: "blur"}
        ],
        contacts: [
          {required: true, message: "岗位编码不能为空", trigger: "blur"}
        ],
        phone: [
          {required: true, message: "岗位顺序不能为空", trigger: "blur"}
        ]
      },
      commonData: commonData,
      select: [],
      sonLine: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listLeave(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: '', // 名称
        deptIds: 0, //参与部门
        userIds: 0, //参与用户
        isMoney: 0, //是否带薪
        unit: '3', //单位1-天2-半天3-小时
      };
      this.scope = 1
      this.cascaderData = []
      this.resetForm("form");
      this.select = []
      this.sonLine = {}
    },
    detelData(index) {
      console.log('index=>', index)
      delete this.sonLine[index]
    },
    selectOrg() {
      this.$refs.orgPicker.show()
    },
    selected(select) {
      this.select = Object.assign([], select)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // getUser().then(response => {
      //   this.postOptions = response.posts;
      //   this.roleOptions = response.roles;
      //   this.open = true;
      //   this.title = "添加用户";
      //   this.form.password = this.initPassword;
      // });
      this.reset();
      this.open = true;
      this.title = "新建请假规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.id || this.ids
      getLeave(postId).then(response => {
        delete response.data.detail.dept
        console.log('response:', response) // sonLine
        let list = []
        if(response.data.depts){
          for (let item of response.data.depts) {
            list.push({
              id: item.deptId,
              name: item.deptName,
              type: 'dept',
              selected: true
            })
          }
        }
        for (let item of response.data.users) {
          list.push({
            id: item.userId,
            name: item.nickName,
            type: 'user',
            selected: true
          })
        }
        this.select = this.$deepCopy(list)
        this.scope = response.data.detail.deptIds !== '0' ? 2 : 1
        this.sonLine = JSON.parse(response.data.detail.content)
        // scope: 1,
        response.data.detail.unit = response.data.detail.unit.toString()
        this.form = response.data.detail;
        this.open = true;
        this.title = "编辑请假规则";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log('this.sonLine===>', this.sonLine, this.select)
      this.$refs["form"].validate(valid => {
        if (valid) {
          let query_ = this.$deepCopy(this.form)
          let id_ = []
          for (let item of this.select) {
            id_.push(item.id)
          }
          if (this.scope == 1) {
            query_.inDept = 0
          } else {
            query_.inDept = id_.join(',')  // inDept 已选
          }
          let parents_ = []
          let son_ = []
          for (let index in this.sonLine) {
            parents_.push(Number(index))
            son_ = this.combineUnique(son_, this.sonLine[index])
          }
          query_.deptIds = this.combineUnique(son_, parents_).join(',') || '0' // deptIds 全部
          query_.content = JSON.stringify(this.sonLine) // content 自定义任意数据格式

          console.log('query_==>', query_)
          if (query_.id != undefined) {
            updateLeave(query_).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLeave(query_).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    combineUnique(...arrays) {
      // 使用Set去除重复元素
      const uniqueElements = new Set([].concat(...arrays));
      // 将Set对象转换回数组
      return [...uniqueElements];
    },
    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.nickName + '"客户吗？').then(function () {
        return updateLeave({userId: row.userId, status: row.status});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除"' + row.name + '"的数据项？').then(function () {
        return delLeave(postIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    },
    sonIdfn(option) {
      console.log('收到的信息：', option)
      this.sonLine = this.$deepCopy(option)
    }
  }
};
</script>
